import axios from 'axios';

export default class Api {
	server;
	constructor(host) {
		this.server = axios.create({
			baseURL: host,
			timeout: 3000,
			withCredentials: false,
			headers: {
				'X-Custom-Header': 'foobar',
			}
		});
		this.server.interceptors.request.use((config) => {
			const item = JSON.parse(sessionStorage.getItem('authorization'));
			if (item !== null) {
				// eslint-disable-next-line no-param-reassign
				config.headers = {
					...config.headers,
					'Authorization': item,
				};

			} else {
				// eslint-disable-next-line no-param-reassign
				config.headers = {
					...config.headers,
				};
			}

			if (config.data instanceof FormData && item !== null) {
				// eslint-disable-next-line no-param-reassign
				config.headers = {
					...config.headers,
					'Content-Type': 'multipart/form-data',
					'Authorization': item,
				};
			}
			return config;
		}, function (err) {
			return Promise.reject(err);
		});
		this.server.interceptors.response.use((response) => {
			const item = JSON.parse(sessionStorage.getItem('authorization'));
			/**
			 * 第一次登录时候就session，后面session就不为空了，所以也就不需要再次session了
			 */
			if (item === null) {
				const authorization = response.headers.authorization === undefined ? null : response.headers.authorization;
				sessionStorage.setItem("authorization", JSON.stringify(authorization));
			}
			return response;
		}, function (err) {
			return Promise.reject(err);
		});
	}

	connection(method = 'get', url, body) {
		let data = null;
		if (method === 'get' || method === 'delete') {
			data = async (resolve, reject) => {
				try {
					const result = await this.server({
						method: method,
						url: url,
						params: body
					});
					resolve(result.data);
				} catch (err) {
					reject(err.toString());
				}
			};
		} else {
			data = async (resolve, reject) => {
				try {
					const result = await this.server({
						method: method,
						url: url,
						data: body
					});
					resolve(result.data);
				} catch (err) {
					reject(err.toString());
				}
			};
		}
		return new Promise(data);
	}
}
